<?php

namespace App\Jobs;

use App\Models\FormIds;
use App\Models\TemplatesLog;
use App\Models\TmplmsgsLog;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Cache\Simple\RedisCache;

class PushJobs implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected  $openid;
    protected  $template;
    public function __construct($openid,$template)
    {
        $this->openid = $openid;
        $this->template = $template;
    }

    public function handle()
    {
        try {
            //根据openid去数据库查询一条有效的formid信息
            $message = FormIds::select('formid')->where('openid',$this->openid)
            ->where('expires_at','>',Carbon::now()->addHours(1))
            ->first();
            if($message){
                $sendData = [
                    'touser' => $this->openid,
                    'template_id' => $this->template['template_id'],
                    'page' => $this->template['page'],
                    'form_id' => $message['formid'],
                    'data' => $this->template['keyword'][0],
                    'emphasis_keyword' => isset($this->template['emphasis']) ? $this->template['emphasis'].".DATA" : '',
                ];
                //小程序实例化
                $app = app('wechat.mini_program');
                $predis = app('redis')->connection()->client();
                $cache = new RedisCache($predis);
                $app->rebind('cache', $cache);
                $data = $app->template_message->send($sendData);
                Log::info($data);
                if($data['errcode'] == 0){
                    //成功直接删除该formid信息
                    FormIds::where('formid',$message['formid'])->delete();
                    //更新推送记录
                    TmplmsgsLog::where('template_id',$this->template['template_id'])
                        ->whereDate('created_at',Carbon::now()->toDateString())
                        ->increment('number');
                    //更新openid记录
                    TemplatesLog::where('openid',$this->openid)
                        ->where('template_id',$this->template['template_id'])
                        ->where('created_at',Carbon::now()->toDateString())
                        ->increment('status');
                }
                //记录推送失败,form_id不正确，或者过期,或者被使用，直接删除记录
                if(($data['errcode'] == 41028) || ($data['errcode'] == 41029)){
                    //这种错误重新生成该openid的推送队列
                    dispatch((new PushJobs($this->openid,$this->template))->onQueue('daduizhang_push'));
                    FormIds::where('formid',$message['formid'])->delete();
                }

            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
    }

    public function failed(\Exception $e)
    {
        Log::error($e->getMessage());
    }




}
